<div class="mdui-toolbar">
    <button class="mdui-btn mdui-btn-icon" mdui-menu="{target: '#filter-menu'}" id="filter-button"
        mdui-tooltip="{content: '筛选'}">
        <i class="mdui-icon material-icons">filter_list</i>
    </button>
    <div class="mdui-menu" id="filter-menu" style="transform-origin: 100% 0px; position: fixed;">
        <div class="mdui-textfield">
            <label class="mdui-textfield-label">编号 ID</label>
            <input class="mdui-textfield-input" type="text" id='where_id' />
        </div>
        <div class="mdui-textfield">
            <label class="mdui-textfield-label">名称</label>
            <input class="mdui-textfield-input" type="text" id='where_name' />
        </div>
        <div class="mdui-textfield">
            <label class="mdui-textfield-label">链接 URL</label>
            <input class="mdui-textfield-input" type="text" id='where_url' />
        </div>
        <div class="mdui-textfield">
            <label class="mdui-textfield-label">搜索</label>
            <input class="mdui-textfield-input" type="text" id='where_search' />
        </div>
    </div>
    <select class="mdui-select" id="sort-select" mdui-select="{position: 'bottom'}">
        <option value="id,0">ID ↑</option>
        <option value="id,1" selected>ID ↓</option>
        <option value="name,0">名称 ↑</option>
        <option value="name,1">名称 ↓</option>
    </select>
    <div class="mdui-toolbar-spacer"></div>
    <button class="mdui-btn mdui-btn-icon" id="add_banner" mdui-tooltip="{content: '添加'}">
        <i class="mdui-icon material-icons">add</i>
    </button>
    <button class="mdui-btn mdui-btn-icon" id="update" mdui-tooltip="{content: '刷新'}">
        <i class="mdui-icon material-icons">refresh</i>
    </button>
</div>
<div id="table"></div>
<div class="mdui-btn-group pages"></div>
<style>
    .ds-table {
        height: calc(100% - 57px - 57px);
        border-top: 1px solid rgba(0, 0, 0, .12);
        border-bottom: 1px solid rgba(0, 0, 0, .12);
    }
</style>
<script>
    !function () {
        var $ = mdui.$;
        var tb = new table.T($("#table"));

        tb.addField("#");
        tb.addField("ID");
        tb.addField("名称");
        tb.addField("URL");
        tb.addField("操作");

        var loading = false; // 加载中

        var page = 1; // 当前页
        var size = 1; // 总页数

        var sort_field = 'id'; // 进行排序的字段
        var sort_type = '1'; // 排序方式：0升序1降序

        var where_id = ''; // 筛选数据：ID
        var where_name = ''; // 筛选数据：名称
        var where_url = ''; // 筛选数据：链接URL
        var where_search = ''; // 筛选数据：搜索

        $('#update').on('click', update);
        $('#add_banner').on('click', addNewThing);
        $('#sort-select').on('change', () => {
            var v = $('#sort-select').val();
            sort_field = v.split(',')[0];
            sort_type = v.split(',')[1];
            page = 1;
            update();
        });
        $('#where_id').on('change', () => {
            where_id = $('#where_id').val();
            page = 1;
            update();
        });
        $('#where_name').on('change', () => {
            where_name = $('#where_name').val();
            page = 1;
            update();
        })
        $('#where_url').on('change', () => {
            where_url = $('#where_url').val();
            page = 1;
            update();
        })
        $('#where_search').on('change', () => {
            where_search = $('#where_search').val();
            page = 1;
            update();
        })

        function isFilter() {
            return where_id || where_name || where_url || where_search;
        }

        function update() {
            if (loading) return;
            loading = true;

            $('#filter-button')[isFilter() ? 'addClass' : 'removeClass']('mdui-text-color-theme')

            renderPages();
            tb.clear();
            tb.startLoading();

            $.ajax({
                url: "./api/get_new_things_list?p=" + page +
                    '&sort_field=' + encodeURIComponent(sort_field) +
                    '&sort_type=' + encodeURIComponent(sort_type) +
                    '&where_id=' + encodeURIComponent(where_id) +
                    '&where_name=' + encodeURIComponent(where_name) +
                    '&where_url=' + encodeURIComponent(where_url) +
                    '&where_search=' + encodeURIComponent(where_search),
                dataType: "json",
                success: function (res) {
                    if (res.code == 200) {
                        tb.endLoading();
                        loading = false;

                        size = res.data.size;

                        if (size) {
                            $('.pages').show();
                            var data = res.data.data
                            for (let d of data) {
                                let change = $(`<button class="mdui-btn mdui-btn-icon" mdui-tooltip="{content: '更改'}"><i class="mdui-icon material-icons">create</i></button>`)
                                let remove = $(`<button class="mdui-btn mdui-btn-icon" mdui-tooltip="{content: '删除'}"><i class="mdui-icon material-icons">delete</i></button>`)

                                change.on('click', function () {
                                    changeBanner(d.id);
                                })

                                remove.on('click', function () {
                                    removeBanner(d.id);
                                })

                                // 图片预览
                                tb.addRow([
                                    d.id,
                                    d.name,
                                    d.url,
                                    {
                                        type: 'el',
                                        el: $('<div></div>').append(change).append(remove)
                                    }
                                ]);
                            }
                        } else {
                            $('.pages').hide();
                        }
                        renderPages();
                    }
                    else {
                        mdui.snackbar(res.msg || "加载失败")
                    }
                }
            });
        }

        function renderPages() {
            $(".pages").html('');
            var omit = true; // 是否省略

            // 添加向左翻页按钮
            var left = $(`<button class="mdui-btn left">&lt;</button>`)
            left.appendTo($(".pages"));

            for (let i = 0; i < size; i++) {
                let toadd = false; // 是否要添加页数按钮

                if (i === 0) toadd = true; // 第一页要添加
                if (i === size - 1) toadd = true; // 最后一页要添加
                if (i - page < 2 && i - page > -4) toadd = true; // 如果与当前页的距离小于2，则添加
                if (page < 5 && i < 7) toadd = true; // 如果当前页小于5，则前7页都要添加
                if (page > size - 5 && i > size - 7) toadd = true; // 如果当前页在倒数5页范围内，则倒数7页都要添加

                if (toadd) {
                    // 渲染页数按钮
                    let button = $(`<button class="mdui-btn ${(i + 1) == page ? `mdui-btn-active` : ""} page-num">${i + 1}</button>`);
                    button.on("click", () => { // 点击事件
                        page = Number(i + 1);
                        update();
                    })
                    button.appendTo($(".pages"));
                    omit = true;
                } else {
                    if (omit) {
                        $(`<button class="mdui-btn" disabled>...</button>`).appendTo($(".pages"));
                        omit = false;
                    }
                }
            }

            // 添加向右翻页按钮
            var right = $(`<button class="mdui-btn right">&gt;</button>`)
            right.appendTo($(".pages"));

            // 根据条件禁用按钮
            left.prop("disabled", page === 1);
            right.prop("disabled", page === size)

            // 添加点击事件
            left.on("click", () => { // 向左
                page -= 1
                update();
            })

            right.on("click", () => { // 向右
                page += 1
                update();
            })
        }

        function addNewThing() {
            var saving = false;

            const dialog = $.dialog({
                title: '添加新品',
                history: false,
                cssClass: "ds-loadable",
                content: `
        <div class="mdui-textfield">
                <label class="mdui-textfield-label">名称</label>
                <input class="mdui-textfield-input" type="text" id='ds-add-name' placeholder="输入新品名称" required>
                <div class="mdui-textfield-error">名称不能为空</div>
            </div>
        <div class="mdui-textfield">
            <label class="mdui-textfield-label">链接 URL</label>
            <input class="mdui-textfield-input" type="text" id='ds-add-url' required>
            <div class="mdui-textfield-error">URL不能为空</div>
        </div>
<div class="mdui-spinner"></div>`,
                buttons: [{
                    text: '取消',
                    close: false,
                    onClick() {
                        if (content.find('.mdui-spinner').length || saving) return false;
                        dialog.close();
                    }
                }, {
                    text: '保存',
                    close: false,
                    onClick: function () {
                        if (content.find('.mdui-spinner').length || saving) return false;
                        const name = content.find('#ds-add-name').val();
                        const url = content.find('#ds-add-url').val();

                        if (!name || !url) {
                            return mdui.snackbar('请填写完整信息');
                        }

                        content.find('input,a,select').attr('disabled', '');
                        saving = true;

                        // 创建FormData上传文件
                        const formData = {
                            name: name,
                            url: url
                        };

                        addBannerApi(formData)
                            .then(() => {
                                dialog.close();
                                update();
                                saving = false;
                                return mdui.snackbar("添加成功")
                            }, (msg) => {
                                saving = false;
                                content.find('input,a,select').removeAttr('disabled');
                                return window.parent.mdui.snackbar(msg || "添加失败")
                            });
                    },
                }]
            });

            const content = dialog.$element

            window.parent.mdui.mutation();
            content.find('.mdui-spinner').remove();
        }

        function addBannerApi(formData) {
            return new Promise((resolve, reject) => {
                $.ajax({
                    url: "./api/add_new_thing",
                    method: 'POST',
                    data: formData,

                    dataType: "json",
                    success: function (res) {
                        if (res.code == 200) {
                            resolve()
                        } else {
                            reject(res.msg)
                        }
                    },
                    error: function (res) {
                        reject(res.responseJSON?.msg || "网络错误")
                    }
                });
            })
        }

        function changeNewThing(id) {
            var saving = false;

            const dialog = $.dialog({
                title: '修改新品',
                history: false,
                cssClass: "ds-loadable",
                content: `
        <div class="mdui-textfield">
                <label class="mdui-textfield-label">名称</label>
                <input class="mdui-textfield-input" type="text" id='ds-change-name' placeholder="输入新品名称" required>
                <div class="mdui-textfield-error">名称不能为空</div>
            </div>
        <div class="mdui-textfield">
            <label class="mdui-textfield-label">链接 URL</label>
            <input class="mdui-textfield-input" type="text" id='ds-change-url' required>
            <div class="mdui-textfield-error">URL不能为空</div>
        </div>
<div class="mdui-spinner"></div>`,
                buttons: [{
                    text: '取消',
                    close: false,
                    onClick() {
                        if (content.find('.mdui-spinner').length || saving) return false;
                        dialog.close();
                    }
                }, {
                    text: '保存',
                    close: false,
                    onClick: function () {
                        if (content.find('.mdui-spinner').length || saving) return false;
                        const name = content.find('#ds-change-name').val();
                        const url = content.find('#ds-change-url').val();

                        if (!name || !url) {
                            return mdui.snackbar('请填写URL');
                        }

                        content.find('input,a,select').attr('disabled', '');
                        saving = true;

                        // 创建FormData上传文件
                        const formData = {
                            id: id,
                            name: name,
                            url: url
                        };

                        changeBannerApi(id, formData)
                            .then(() => {
                                dialog.close();
                                update();
                                saving = false;
                                return mdui.snackbar("修改成功")
                            }, (msg) => {
                                saving = false;
                                content.find('input,a,select').removeAttr('disabled');
                                return window.parent.mdui.snackbar(msg || "修改失败")
                            });
                    },
                }]
            });

            const content = dialog.$element

            window.parent.mdui.mutation();

            $.ajax({
                url: "./api/get_banner_info?id=" + id,
                dataType: "json",
                success: function (res) {
                    if (res.code != 200) {
                        dialog.close();
                        return mdui.snackbar(res.msg || "加载失败")
                    }

                    const data = res.data;
                    content.find('#ds-change-name').val(data.name);
                    content.find('#ds-change-url').val(data.url);

                    window.parent.mdui.updateTextFields();
                    window.parent.mdui.mutation();

                    content.find('.mdui-spinner').remove();
                    dialog.handleUpdate();

                }
            });
        }

        function changeBannerApi(id, formData) {
            return new Promise((resolve, reject) => {

                let formData = {
                    id: id,
                    url: url
                };
                if (img_url) {
                    formData.img_url = img_url;
                }
                $.ajax({
                    url: "./api/change_new_thing_info",
                    method: 'POST',
                    data: formData,
                    // 创建普通对象提交数据
                    dataType: "json",
                    success: function (res) {
                        if (res.code == 200) {
                            resolve()
                        } else {
                            reject(res.msg)
                        }
                    },
                    error: function (res) {
                        reject(res.responseJSON?.msg || "网络错误")
                    }
                });
            })
        }

        function removeNewThing(id) {
            mdui.$.confirm('确定要删除这个新品吗？', '确认删除', function () {
                $.ajax({
                    url: './api/delete_new_thing',
                    method: 'POST',
                    data: { id: id },
                    dataType: "json",
                    success: function (res) {
                        if (res.code === 200) {
                            window.parent.mdui.snackbar("删除成功")
                            update();
                        } else {
                            window.parent.mdui.snackbar(res.msg || "删除失败");
                        }
                    }
                });
            });
        }

        update();
    }();
</script>